import { Component, OnInit, ViewChild, Inject, Injector } from '@angular/core';
import { NgForm } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { WhitelistService } from '../../services/whitelist.service';
import { DatePipe } from '@angular/common';
import { DetailBase } from 'app/modules/base/detail-base';

@Component({
  selector: 'm-whitelist-edit',
  templateUrl: './whitelist-edit.component.html',
  styleUrls: ['./whitelist-edit.component.scss'],
  providers: [DatePipe],
})
export class WhitelistEditComponent extends DetailBase implements OnInit {
  @ViewChild(NgForm) ngForm: NgForm;
  submitting: boolean = false;
  formGroup = this.fb.group({
    alias_name: [''],
    remaining_date: [''],
    remarks: [''],
    permanent: false,
  });
  constructor(
    private injector: Injector,
    private whitelistService: WhitelistService,
    private datePipe: DatePipe,
    @Inject(MAT_DIALOG_DATA) public data: any,
    public dialogRef: MatDialogRef<WhitelistEditComponent>,
  ) {
    super(injector);
  }

  ngOnInit() {
    setTimeout(() => {
      const expiry_date = new Date(this.data.expiry_date);
      let remaining_date;
      if (expiry_date.getUTCFullYear() === 2120) {
        this.formGroup.get('remaining_date').disable();
        this.formGroup.patchValue(Object.assign({}, this.data, { permanent: true }));
      } else {
        remaining_date = {
          year: expiry_date.getFullYear(),
          month: expiry_date.getMonth() + 1,
          day: expiry_date.getDate(),
        };
        this.formGroup.patchValue(Object.assign({}, this.data, { remaining_date: remaining_date }));
      }
    });
  }

  async submit() {
    if (this.formGroup.invalid) {
      return;
    }
    const payload = this.formGroup.getRawValue();
    if (payload.remaining_date) {
      payload.remaining_date = new Date(
        payload.remaining_date.year,
        payload.remaining_date.month - 1,
        payload.remaining_date.day,
      ).toISOString();
    } else {
      delete payload.remaining_date;
      delete payload.permanent;
    }
    await this.whitelistService.update(this.data.id, payload);
    this.cancel();
    this.reload();
  }

  cancel() {
    this.dialogRef.close();
  }

  permanent() {
    if (this.formGroup.get('permanent').value) {
      const remaining_date = this.formGroup.get('remaining_date');
      remaining_date.disable();
      remaining_date.reset();
    } else {
      const expiry_date = new Date();
      const formated_expiry_date = {
        year: expiry_date.getFullYear(),
        month: expiry_date.getMonth() + 1,
        day: expiry_date.getDate(),
      };
      this.formGroup.get('remaining_date').enable();
      this.formGroup.get('remaining_date').setValue(formated_expiry_date);
    }
  }
}
